"""RPA框架的自定义异常类定义"""

class RPAException(Exception):
    """RPA框架的基础异常类"""
    
    def __init__(self, message: str, error_code: str = None, cause: Exception = None):
        """
        初始化RPA基础异常
        
        Args:
            message: 异常消息
            error_code: 错误代码（可选）
            cause: 导致此异常的原始异常（可选）
        """
        self.error_code = error_code or "RPA_ERROR"
        self.cause = cause
        super().__init__(f"[{self.error_code}] {message}")
        
        # 保留原始异常的堆栈信息
        if cause:
            self.__cause__ = cause

class RobotExecutionException(RPAException):
    """机器人执行异常"""
    
    def __init__(self, message: str, error_code: str = "ROBOT_EXECUTION_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class TaskExecutionException(RPAException):
    """任务执行异常"""
    
    def __init__(self, message: str, task_name: str = None, error_code: str = "TASK_EXECUTION_ERROR", cause: Exception = None):
        self.task_name = task_name
        task_info = f"任务 '{task_name}' " if task_name else ""
        super().__init__(f"{task_info}{message}", error_code, cause)

class WorkflowException(RPAException):
    """工作流异常"""
    
    def __init__(self, message: str, workflow_name: str = None, error_code: str = "WORKFLOW_ERROR", cause: Exception = None):
        self.workflow_name = workflow_name
        workflow_info = f"工作流 '{workflow_name}' " if workflow_name else ""
        super().__init__(f"{workflow_info}{message}", error_code, cause)

class ConfigException(RPAException):
    """配置异常"""
    
    def __init__(self, message: str, config_key: str = None, error_code: str = "CONFIG_ERROR", cause: Exception = None):
        self.config_key = config_key
        config_info = f"配置项 '{config_key}' " if config_key else ""
        super().__init__(f"{config_info}{message}", error_code, cause)

class FileNotFoundException(RPAException):
    """文件未找到异常"""
    
    def __init__(self, message: str, file_path: str = None, error_code: str = "FILE_NOT_FOUND", cause: Exception = None):
        self.file_path = file_path
        file_info = f"文件 '{file_path}' " if file_path else ""
        super().__init__(f"{file_info}{message}", error_code, cause)

class ImageProcessingException(RPAException):
    """图像处理异常"""
    
    def __init__(self, message: str, image_path: str = None, error_code: str = "IMAGE_PROCESSING_ERROR", cause: Exception = None):
        self.image_path = image_path
        image_info = f"图像 '{image_path}' " if image_path else ""
        super().__init__(f"{image_info}{message}", error_code, cause)

class ImageNotFoundException(RPAException):
    """图像未找到异常"""
    
    def __init__(self, message: str, search_area: str = None, error_code: str = "IMAGE_NOT_FOUND", cause: Exception = None):
        self.search_area = search_area
        area_info = f"搜索区域 '{search_area}' " if search_area else ""
        super().__init__(f"{area_info}{message}", error_code, cause)

class StringProcessingException(RPAException):
    """字符串处理异常"""
    
    def __init__(self, message: str, error_code: str = "STRING_PROCESSING_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class DateProcessingException(RPAException):
    """日期处理异常"""
    
    def __init__(self, message: str, error_code: str = "DATE_PROCESSING_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class DesktopAutomationException(RPAException):
    """桌面自动化异常"""
    
    def __init__(self, message: str, action: str = None, error_code: str = "DESKTOP_AUTOMATION_ERROR", cause: Exception = None):
        self.action = action
        action_info = f"操作 '{action}' " if action else ""
        super().__init__(f"{action_info}{message}", error_code, cause)

class BrowserAutomationException(RPAException):
    """浏览器自动化异常"""
    
    def __init__(self, message: str, browser_type: str = None, error_code: str = "BROWSER_AUTOMATION_ERROR", cause: Exception = None):
        self.browser_type = browser_type
        browser_info = f"浏览器 '{browser_type}' " if browser_type else ""
        super().__init__(f"{browser_info}{message}", error_code, cause)

class ElementNotFoundException(BrowserAutomationException):
    """元素未找到异常"""
    
    def __init__(self, message: str, locator: str = None, locator_type: str = None, 
                 error_code: str = "ELEMENT_NOT_FOUND", cause: Exception = None):
        self.locator = locator
        self.locator_type = locator_type
        locator_info = f"元素 '{locator}' (类型: {locator_type}) " if locator else ""
        super().__init__(f"{locator_info}{message}", error_code=error_code, cause=cause)

class TimeoutException(RPAException):
    """超时异常"""
    
    def __init__(self, message: str, timeout_seconds: int = None, error_code: str = "TIMEOUT_ERROR", cause: Exception = None):
        self.timeout_seconds = timeout_seconds
        timeout_info = f"(超时: {timeout_seconds}秒) " if timeout_seconds is not None else ""
        super().__init__(f"{message} {timeout_info}", error_code, cause)

class ValidationException(RPAException):
    """验证异常"""
    
    def __init__(self, message: str, field_name: str = None, error_code: str = "VALIDATION_ERROR", cause: Exception = None):
        self.field_name = field_name
        field_info = f"字段 '{field_name}' " if field_name else ""
        super().__init__(f"{field_info}{message}", error_code, cause)

class SecurityException(RPAException):
    """安全异常"""
    
    def __init__(self, message: str, error_code: str = "SECURITY_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class DatabaseException(RPAException):
    """数据库异常"""
    
    def __init__(self, message: str, operation: str = None, error_code: str = "DATABASE_ERROR", cause: Exception = None):
        self.operation = operation
        operation_info = f"操作 '{operation}' " if operation else ""
        super().__init__(f"{operation_info}{message}", error_code, cause)

class NetworkException(RPAException):
    """网络异常"""
    
    def __init__(self, message: str, url: str = None, error_code: str = "NETWORK_ERROR", cause: Exception = None):
        self.url = url
        url_info = f"URL '{url}' " if url else ""
        super().__init__(f"{url_info}{message}", error_code, cause)

# 特定场景的异常类
class AuthenticationException(SecurityException):
    """认证异常"""
    
    def __init__(self, message: str = "认证失败", error_code: str = "AUTHENTICATION_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class AuthorizationException(SecurityException):
    """授权异常"""
    
    def __init__(self, message: str = "权限不足", error_code: str = "AUTHORIZATION_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

class ResourceNotFoundException(RPAException):
    """资源未找到异常"""
    
    def __init__(self, message: str, resource_type: str = None, resource_id: str = None,
                 error_code: str = "RESOURCE_NOT_FOUND", cause: Exception = None):
        self.resource_type = resource_type
        self.resource_id = resource_id
        resource_info = f"{resource_type} '{resource_id}' " if resource_type and resource_id else ""
        super().__init__(f"{resource_info}{message}", error_code, cause)

class ResourceLockedException(RPAException):
    """资源锁定异常"""
    
    def __init__(self, message: str, resource_type: str = None, resource_id: str = None,
                 error_code: str = "RESOURCE_LOCKED", cause: Exception = None):
        self.resource_type = resource_type
        self.resource_id = resource_id
        resource_info = f"{resource_type} '{resource_id}' " if resource_type and resource_id else ""
        super().__init__(f"{resource_info}{message}", error_code, cause)

class RateLimitExceededException(NetworkException):
    """速率限制异常"""
    
    def __init__(self, message: str = "请求速率限制超出", retry_after: int = None,
                 error_code: str = "RATE_LIMIT_EXCEEDED", cause: Exception = None):
        self.retry_after = retry_after  # 建议重试时间（秒）
        retry_info = f"，建议 {retry_after} 秒后重试" if retry_after is not None else ""
        super().__init__(f"{message}{retry_info}", error_code, cause)

class UnexpectedResultException(RPAException):
    """意外结果异常"""
    
    def __init__(self, message: str, expected: any = None, actual: any = None,
                 error_code: str = "UNEXPECTED_RESULT", cause: Exception = None):
        self.expected = expected
        self.actual = actual
        
        # 添加期望值和实际值信息
        details = []
        if expected is not None:
            details.append(f"期望: {expected}")
        if actual is not None:
            details.append(f"实际: {actual}")
            
        full_message = message
        if details:
            full_message = f"{message} ({', '.join(details)})"
            
        super().__init__(full_message, error_code, cause)

# 批量操作相关异常
class BatchProcessingException(RPAException):
    """批量处理异常"""
    
    def __init__(self, message: str, processed_count: int = None, failed_count: int = None,
                 error_code: str = "BATCH_PROCESSING_ERROR", cause: Exception = None):
        self.processed_count = processed_count
        self.failed_count = failed_count
        
        # 添加批量处理统计信息
        stats = []
        if processed_count is not None:
            stats.append(f"已处理: {processed_count}")
        if failed_count is not None:
            stats.append(f"失败: {failed_count}")
            
        full_message = message
        if stats:
            full_message = f"{message} ({', '.join(stats)})"
            
        super().__init__(full_message, error_code, cause)

# 自定义断言异常
class AssertionException(RPAException):
    """断言异常"""
    
    def __init__(self, message: str, error_code: str = "ASSERTION_ERROR", cause: Exception = None):
        super().__init__(message, error_code, cause)

# 第三方服务异常
class ThirdPartyServiceException(RPAException):
    """第三方服务异常"""
    
    def __init__(self, message: str, service_name: str = None, service_error: str = None,
                 error_code: str = "THIRD_PARTY_SERVICE_ERROR", cause: Exception = None):
        self.service_name = service_name
        self.service_error = service_error
        
        service_info = []
        if service_name:
            service_info.append(f"服务: {service_name}")
        if service_error:
            service_info.append(f"错误: {service_error}")
            
        full_message = message
        if service_info:
            full_message = f"{message} ({', '.join(service_info)})"
            
        super().__init__(full_message, error_code, cause)

# 机器人状态异常
class RobotStateException(RobotExecutionException):
    """机器人状态异常"""
    
    def __init__(self, message: str, current_state: str = None, expected_state: str = None,
                 error_code: str = "ROBOT_STATE_ERROR", cause: Exception = None):
        self.current_state = current_state
        self.expected_state = expected_state
        
        state_info = []
        if current_state:
            state_info.append(f"当前状态: {current_state}")
        if expected_state:
            state_info.append(f"期望状态: {expected_state}")
            
        full_message = message
        if state_info:
            full_message = f"{message} ({', '.join(state_info)})"
            
        super().__init__(full_message, error_code, cause)

# 任务状态异常
class TaskStateException(TaskExecutionException):
    """任务状态异常"""
    
    def __init__(self, message: str, task_name: str = None, current_state: str = None, expected_state: str = None,
                 error_code: str = "TASK_STATE_ERROR", cause: Exception = None):
        self.current_state = current_state
        self.expected_state = expected_state
        
        state_info = []
        if current_state:
            state_info.append(f"当前状态: {current_state}")
        if expected_state:
            state_info.append(f"期望状态: {expected_state}")
            
        full_message = message
        if state_info:
            full_message = f"{message} ({', '.join(state_info)})"
            
        super().__init__(full_message, task_name, error_code, cause)